package com.example.userservice.service.impl;

import com.example.userservice.mapper.UserContactApplyMapper;
import com.example.userservice.mapper.UserContactMapper;
import com.example.userservice.mapper.UserInfoMapper;
import com.example.userservice.rabbitmq.publisher.UserPublisher;
import com.example.userservice.service.UserContactApplyService;
import com.example.userservice.service.UserContactService;
import org.example.config.redis.RedisComponent;
import org.example.entity.constants.ConstansMsgType;
import org.example.entity.constants.Constants;
import org.example.entity.dto.*;
import org.example.entity.enums.*;
import org.example.entity.po.*;
import org.example.entity.query.SimplePage;
import org.example.entity.query.UserContactApplyQuery;
import org.example.entity.query.UserContactQuery;
import org.example.entity.query.UserInfoQuery;
import org.example.entity.vo.PaginationResultVO;
import org.example.exception.BusinessException;
import org.example.openFeign.GroupClient;
import org.example.utils.StringTools;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 联系人 业务接口实现
 */
@Service("userContactService")
public class UserContactServiceImpl implements UserContactService {

    @Resource
    private UserContactMapper<UserContact, UserContactQuery> userContactMapper;


    @Resource
    private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;

    @Resource
    private RedisComponent redisComponet;

    @Resource
    private UserContactApplyMapper<UserContactApply, UserContactApplyQuery> userContactApplyMapper;

    @Resource
    private UserContactApplyService userContactApplyService;

    @Resource
    private GroupClient groupClient;
    @Resource
    private UserPublisher userPublisher;
    /**
     * 根据条件查询列表
     */
    @Override
    public List<UserContact> findListByParam(UserContactQuery param) {
        return this.userContactMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(UserContactQuery param) {
        return this.userContactMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<UserContact> findListByPage(UserContactQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<UserContact> list = this.findListByParam(param);
        PaginationResultVO<UserContact> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(UserContact bean) {
        return this.userContactMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<UserContact> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userContactMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<UserContact> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userContactMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(UserContact bean, UserContactQuery param) {
        StringTools.checkParam(param);
        return this.userContactMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(UserContactQuery param) {
        StringTools.checkParam(param);
        return this.userContactMapper.deleteByParam(param);
    }

    @Override
    public UserContactSearchResultDto searchContact(String userId, String contactId) {
        UserContactSearchResultDto dto = new UserContactSearchResultDto();
        UserContactTypeEnum byPrefix = UserContactTypeEnum.getByPrefix(contactId);
        if (byPrefix == null){
            return null;
        }
        switch (byPrefix){
            case USER:
                UserInfo userInfo = userInfoMapper.selectByUserId(contactId);
                if (userInfo == null){
                    throw new BusinessException("没有此人或群聊");
                }
                BeanUtils.copyProperties(userInfo,dto);
                break;
            case GROUP:
                //TODO 待完成
                String string = UUID.randomUUID().toString();
                MessageDto msgDto = new MessageDto();
                msgDto.setMsgType(ConstansMsgType.GET_GROUP_INFO);
                msgDto.setMsgId(string);
                MessageDto messageDto = userPublisher.userSendMsg2Group4GetInfo(msgDto);
                GroupInfo groupInfo = (GroupInfo) messageDto.getMsg();
//                GroupInfo groupInfo = groupInfoMapper.selectByGroupId(contactId);
//                GroupInfo groupInfo = new GroupInfo();
                if (groupInfo == null){
                    throw new BusinessException("没有此人或群聊");
                }

                dto.setNickName(groupInfo.getGroupName());
                break;
        }
        dto.setContactType(byPrefix.toString());
        dto.setContactId(contactId);

        if (userId.equals(contactId)){
            dto.setStatus(UserContactStatusEnum.FRIEND.getStatus());
            return dto;
        }
        UserContact userContact = userContactMapper.selectByUserIdAndContactId(userId, contactId);

        dto.setStatus(userContact== null ? null : userContact.getStatus());
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addApply(HttpServletRequest request,TokenUserInfoDto tokenUserInfo, String contactId, String applyInfo) {
        //判断是否是好友或是否已经加入群聊
        UserContact userContact = userContactMapper.selectByUserIdAndContactId(tokenUserInfo.getUserId(), contactId);
        if (userContact != null && userContact.getStatus().equals(UserContactStatusEnum.FRIEND.getStatus())){
            throw new BusinessException("对方已经是你好友");
        }

        UserContactApply apply = new UserContactApply();
        UserContactTypeEnum typeEnum = UserContactTypeEnum.getByPrefix(contactId);
        Date curDate = new Date();
        Integer joinType = null;
        String recevieUserId = null;
        //默认申请信息
        applyInfo = applyInfo.isEmpty()? String.format(Constants.APPLY_INFO_TEMPLATE,tokenUserInfo.getNickName()) : applyInfo;

        //如果对方是人
        if (typeEnum == UserContactTypeEnum.USER) {
            recevieUserId = contactId;
            //对方信息
            UserInfo userInfo = userInfoMapper.selectByUserId(contactId);
            joinType = userInfo.getJoinType();
            if (userInfo == null){
                throw new BusinessException("没有此人或账号已注销");
            }
            ////如果不是第一次加
            //判断状态 被拉黑
            if (userContact != null && userContact.getStatus() == UserContactStatusEnum.BLACKLIST_BE.getStatus()) {
                throw new BusinessException("对方已将你拉黑，无法添加好友");
            }
            //判断状态 拉黑对方
            if (userContact != null && userContact.getStatus() == UserContactStatusEnum.BLACKLIST.getStatus()) {
                throw new BusinessException("你已将对方拉黑，无法添加好友");
            }
            //判断状态 已经是好友
            if (userContact != null && userContact.getStatus() == UserContactStatusEnum.FRIEND.getStatus()) {
                throw new BusinessException("已经是好友，无法继续添加");
            }
            //最终
            if (userInfo.getJoinType().equals(JoinTypeEnum.FORBID.getType())){
                throw new BusinessException("对方拒绝加入任何人");
            }
            apply.setContactType(UserContactTypeEnum.USER.getType());
        }else if (typeEnum == UserContactTypeEnum.GROUP){
            GroupInfo groupInfo = (GroupInfo) groupClient.queryGroupByGroupId(request, contactId).getData();
            joinType = groupInfo.getJoinType();
            recevieUserId = groupInfo.getGroupOwnerId();
            if (groupInfo.getStatus().equals(GroupStatusEnum.DISSOLUTION.getStatus())){
                throw new BusinessException("群聊已解散");
            }
            apply.setContactType(UserContactTypeEnum.GROUP.getType());

        }

        //如果是直接加入
        if (joinType.equals(JoinTypeEnum.JOIN.getType())){
            Integer type = null;
            if (typeEnum == UserContactTypeEnum.GROUP){
                type = UserContactTypeEnum.GROUP.getType();
            }else {
                type = UserContactTypeEnum.USER.getType();
            }
            userContactApplyService.addContact(request,recevieUserId,tokenUserInfo.getUserId(),contactId,type,UserContactStatusEnum.FRIEND.getStatus());
            return joinType;
        }

        apply.setApplyInfo(applyInfo);
        apply.setApplyUserId(tokenUserInfo.getUserId());
        apply.setLastApplyTime(curDate.getTime());
        apply.setStatus(UserContactApplyStatusEnum.INIT.getStatus());
        apply.setReceiveUserId(recevieUserId);
        apply.setContactId(contactId);
        UserContactApply contactApply = userContactApplyMapper.selectByApplyUserIdAndReceiveUserIdAndContactId(tokenUserInfo.getUserId(), recevieUserId, contactId);
        if (contactApply == null) {
            userContactApplyMapper.insert(apply);

        }else {
            userContactApplyMapper.updateByApplyId(apply,contactApply.getApplyId());
        }

        //好友没有申请过，或者好友之前拒绝了但是没有拉黑
        if (contactApply == null || !contactApply.getStatus().equals(UserContactApplyStatusEnum.INIT.getStatus())){
            MessageSendDto messageSendDto = new MessageSendDto();
            messageSendDto.setMessageType(MessageTypeEnum.CONTACT_APPLY.getType());
            messageSendDto.setMessageContent(applyInfo);
            messageSendDto.setContactId(recevieUserId);
            userPublisher.sendMessage(messageSendDto);
        }

        return joinType;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRobot4Contact(String userId) {
        UserContact userContact = new UserContact();
        Date curDate = new Date();
        SysSettingDto sysSetting = redisComponet.getSysSetting();
        String welcome = StringTools.cleanHtmlTag(sysSetting.getRobotWelcome());

        userContact.setContactId(sysSetting.getRobotUid());
        userContact.setContactName(sysSetting.getRobotNickName());
        userContact.setUserId(userId);
        userContact.setCreateTime(curDate);
        userContact.setContactType(UserContactTypeEnum.USER.getType());
        userContact.setStatus(UserContactStatusEnum.FRIEND.getStatus());
        userContactMapper.insert(userContact);

        ChatSessionUser chatSessionUser = new ChatSessionUser();
        ChatSession chatSession = new ChatSession();
        String[] attr = {sysSetting.getRobotUid(),userId};
        String sessionId = StringTools.getChatSessionId4User(attr);
        String contactName = sysSetting.getRobotNickName();

        //增加会话消息
        chatSession.setSessionId(sessionId);
        chatSession.setLastMessage(sysSetting.getRobotWelcome());
        chatSession.setLastReceiveTime(curDate.getTime());
        userPublisher.userSendMsg2ChatDB(chatSession);
//        chatSessionService.add(chatSession);

        //增加会话人信息
        chatSessionUser.setUserId(userId);
        chatSessionUser.setContactId(sysSetting.getRobotUid());
        chatSessionUser.setContactName(sysSetting.getRobotNickName());
        chatSessionUser.setSessionId(sessionId);
        userPublisher.userSendMsg2ChatDB(chatSessionUser);
//        chatSessionUserService.add(chatSessionUser);

        //增加聊天消息
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setMessageType(MessageTypeEnum.CHAT.getType());
        chatMessage.setMessageContent(sysSetting.getRobotWelcome());
        chatMessage.setSendUserId(sysSetting.getRobotUid());
        chatMessage.setSendUserNickName(sysSetting.getRobotNickName());
        chatMessage.setSendTime(curDate.getTime());
        chatMessage.setContactId(userId);
        chatMessage.setContactType(UserContactTypeEnum.USER.getType());
        chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
        userPublisher.userSendMsg2Chat(chatMessage);
//        chatMessageMapper.insert(chatMessage);
    }
}